package com.thinkgem.jeesite.modules.cms.web.login;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.servlet.ValidateCodeServlet;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CellPhoneMessage;
import com.thinkgem.jeesite.common.utils.EmailPinCacheUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.JavaMailSend;
import com.thinkgem.jeesite.common.utils.PINCacheUtils;
import com.thinkgem.jeesite.common.utils.SendMailUtil;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.ValidateCode;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfo;
import com.thinkgem.jeesite.modules.accountinfo.service.AccountInfoService;
import com.thinkgem.jeesite.modules.config.service.message.ConfigMessageService;
import com.thinkgem.jeesite.modules.front.entity.cart.GenCart;
import com.thinkgem.jeesite.modules.front.service.cart.GenCartService;
import com.thinkgem.jeesite.modules.product.service.product.GenProductService;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;


@Controller
@RequestMapping(value = "${frontPath}/account")
public class UserLoginController extends BaseController {
    public ValidateCode validateCode= new ValidateCode();
    public CellPhoneMessage cellPhoneMessage = new CellPhoneMessage();
    JavaMailSend mailsend = new JavaMailSend();
    SendMailUtil send = new SendMailUtil();
    @Autowired
    private SystemService systemService;
    
    @Autowired
    private AccountInfoService accountInfoService;

    @Autowired GenProductService genProductService;
    
    @Autowired ConfigMessageService service;
    
    
    @Autowired
    GenCartService genCartService;
    @RequestMapping(value="login${urlSuffix}")
    public String toLogin(HttpServletRequest request,Model model){
    
        String id = (String) SecurityUtils.getSubject().getSession().getId(); 

        if(id!=null){
            model.addAttribute("ssid",id);
        }
        return "modules/account/login";
    }
    
    //登出
    @RequestMapping(value="loginOut")
    public String loginOut(HttpSession session){
        session.setAttribute("user", null);
        return "redirect:" + frontPath + "/account/login.html";
    }
    

    @ResponseBody
    @RequestMapping(value="doLogin")
    public Map<String,String> checkLogin(AccountInfo user,String validateCode,HttpServletRequest request,RedirectAttributes redirectAttributes,Model model,HttpSession session) throws Exception{
        Map<String,String> map = new HashMap<String,String>();
        model.addAttribute("isValidateCodeLogin", true);
        if(StringUtils.isBlank(validateCode)){
            map.put("loginResult", "206");
            return map;
        }else if(!new ValidateCodeServlet().validate(request, validateCode)){
            request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
            map.put("loginResult", "207");
            return map;
        }
        
        if(StringUtils.isBlank(user.getUsername())&&StringUtils.isBlank(user.getTelNum())&&StringUtils.isBlank(user.getEmail())){
           /* addMessage(redirectAttributes,"登录名不可以为空");*/
            map.put("loginResult", "203");
            return map;
        }
        
        AccountInfo account = accountInfoService.validateUser(user);
        if(account!=null){
            account.getPassWord();
            if(account.getUserStatus()==0){
                map.put("loginResult", "204");
                map.put("loginUserId", account.getId());
                map.put("loginUserName", account.getUsername());
                return map; 
            }
          //  String password = systemService.entryptPassword(user.getPassWord());
            if(SystemService.validatePassword(user.getPassWord(),account.getPassWord())){
                
                Object object = CacheUtils.get(account.getId());
                List<GenCart> carts = null;
                if (object != null) {
                    carts  = (List<GenCart>) object;
                } else {
                    GenCart genCart = new GenCart();
                    genCart.setAccountid(Long.parseLong(account.getId()));
                    carts = genCartService.findList(genCart);
                    CacheUtils.put(account.getId(), carts);
                }
                session.setAttribute("carts", carts);
                session.setAttribute("count", carts.size());
                session.setAttribute("user", account);
            }else{
                /*addMessage(redirectAttributes, Message.getContent("密码不正确"));*/
                map.put("loginResult", "202");
                return map;
            }
        }else{
            /*addMessage(redirectAttributes, Message.getContent("用户不存在"));*/
            map.put("loginResult", "201");
            return map;
        }
        map.put("loginResult", "200");
        map.put("loginUserId", account.getId());
        map.put("loginUserName", account.getUsername());
        return map;
    }
    
    @RequestMapping(value="register${urlSuffix}")
    public String toRegister(){
        
        return "modules/account/register";
    }
    
    
    @SuppressWarnings("static-access")
    @ResponseBody
    @RequestMapping(value="doRegister")
    public Map<String,String> doRegister(Model model,AccountInfo user,String confirmPassword,String verificationCode,Boolean registerType,RedirectAttributes redirectAttributes) throws ParseException {
        
        Map<String,String> map = new HashMap<String,String>();
        
        if(StringUtils.isBlank(user.getPassWord())||user.getPassWord().length()>18){
            map.put("result", "201");
            return map;
        }
      
        if(!user.getPassWord().equals(confirmPassword)){
           // addMessage(redirectAttributes, Message.getContent(""));
            map.put("result", "201");
            return map;
        }
        
        if(StringUtils.isBlank(user.getUsername())||user.getUsername().length()>20){
            map.put("result", "202");
            return map;
        }
      
        if(!checkIllegalCharacter(user.getUsername())){
            map.put("result", "202");
            return map;
        }
        Object object=null ;
        if(registerType){
            object = PINCacheUtils.get(user.getTelNum());
            if(StringUtils.isBlank(user.getTelNum())){
                //addMessage(redirectAttributes, Message.getContent("accountinfo.register.phoneNum"));
                map.put("result", "203");
                return map;
            }
        }else{
         //   object = PINCacheUtils.get(user.getEmail());
            
            if(StringUtils.isBlank(user.getEmail())){
               // addMessage(redirectAttributes, Message.getContent("accountinfo.register.phoneNum"));
                map.put("result", "204");
                return map;
            }
        }
        
        if(StringUtils.isBlank(verificationCode)){
            map.put("result", "205");
           // addMessage(redirectAttributes, Message.getContent("accountinfo.register.validateCode"));
            return map;
        }/*else if(!verificationCode.equalsIgnoreCase(object.toString())){
           // addMessage(redirectAttributes, Message.getContent("验证码不正确"));
            map.put("result", "206");
            return map;
        }*/
        user.setPhoneValidateCode(verificationCode);
        Date date = new Date();
      
        user.setCreateTime(date);
        if(user.getTelNum()!=null){
            user.setUserPhoneStatus(1); 
        }else{user.setUserPhoneStatus(0);}
        if(user.getEmail()!=null){
            user.setUserEmailStatus(1);   
        }else{user.setUserEmailStatus(0);}
        user.setPassWord(systemService.entryptPassword(user.getPassWord()));
        user.setUserStatus(1);
        accountInfoService.save(user);
       // addMessage(redirectAttributes, Message.getContent("注册成功"));
        map.put("result", "200");
        return map;
    }
    
    @ResponseBody
    @RequestMapping(value="getVerificationCode")
    public String sendVerificationCode(String telNum,HttpServletResponse response) throws Exception{
        boolean falg = false;
        String code1 =validateCode.createCode(falg,6);
        AccountInfo user = new AccountInfo();
        user.setTelNum(telNum);
        if(accountInfoService.validateAccountInfo(user).size()>0){
           return "此手机号已经注册，请登陆";  
        }
        if(StringUtils.isNotBlank(telNum)){
           cellPhoneMessage.sendPhoneMessage(telNum, code1);
        }
        PINCacheUtils.put(telNum,code1);
        return "验证码已发送";
    }
    
    @ResponseBody
    @RequestMapping("bindMailOrPhone")
    public Map<String,String> bindMailBoxAOrPhone(String id,String email,String verificationCode,String telNum,RedirectAttributes redirectAttributes){
        Map<String,String> map = new HashMap<String,String>();
        if(StringUtils.isNotBlank(id)){
            AccountInfo accountInfo = accountInfoService.get(id);
            if(StringUtils.isNotBlank(email)){
                accountInfo.setEmail(email);
                
            }else if(StringUtils.isBlank(telNum)){
                map.put("dataResult", "201");
                return map;
            }
            if(StringUtils.isNotBlank(telNum)){
                accountInfo.setTelNum(telNum);
                
            }else if(StringUtils.isBlank(email)){
                map.put("dataResult", "202");
                return map;
            }
            if(StringUtils.isBlank(verificationCode)){
                // addMessage(redirectAttributes, Message.getContent("验证码不能为空"));
                 map.put("dataResult", "203");
                 return map;
             }else if(!verificationCode.equalsIgnoreCase(validateCode.validateCode)){
                // addMessage(redirectAttributes, Message.getContent("验证码不正确"));
                 map.put("dataResult", "204");
                 return map;
             }
            accountInfoService.save(accountInfo);
        }
        map.put("dataResult", "200");
        return map;
    }
    
    @ResponseBody
    @RequestMapping(value="bindMail")
    public String bindMailbox(String email){
        boolean falg = false;
        String code1 =validateCode.createCode(falg,6);
        AccountInfo user = new AccountInfo();
        user.setEmail(email);
        if(accountInfoService.validateAccountInfo(user).size()>0){
            return "此邮箱已经注册，请登陆";  
         }
        mailsend.sendMail(code1 , email);
        EmailPinCacheUtils.put(email, code1);
        return "验证码已发送";
    }
    
    //验证码验证
    @ResponseBody
    @RequestMapping(value="vlidateCode")
    public  Map<String,String>  verlicationCode(String valnum,String verificationCode,RedirectAttributes redirectAttributes){
        Map<String,String> map = new HashMap<String,String>();
        Object object =null;
        if(valnum!=null&&valnum!=""){
            if(valnum.contains("@")){
                object = EmailPinCacheUtils.get(valnum);
            }else{
                object = PINCacheUtils.get(valnum);   
            }
        }
         
        if(object==null){
            map.put("valid", "false");
            return map;  
        }
        if(!verificationCode.equalsIgnoreCase(object.toString())){
          //  map.put("vresult", "验证码输入不正确");
            map.put("valid", "false");
            return map;
        }
        map.put("valid", "true");
        return map;
    }
    
    @RequestMapping(value="forgetPassword")
    public String  forgetPassword(){
        
        return "modules/account/forgetPassword";
    }
    
    //验证用户是否存在
    @ResponseBody
    @RequestMapping("validateuser")
    public Map<String,Object> validateuser(AccountInfo user,HttpSession session,RedirectAttributes redirectAttributes) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        if(StringUtils.isBlank(user.getUsername())){
            map.put("result", "200");
            return map;
        }
        AccountInfo accoutInfo= accountInfoService.validateUser(user);
        if(accoutInfo==null){
            map.put("result", "201");
        }else{
            map.put("result",accoutInfo);
        }
        return map;
       
    }
    
    @ResponseBody
    @RequestMapping("phoneOrEmailValidatecode")
    public Object getPhoneOrEmailValidateCode(String username,HttpSession session ) throws Exception{
    //    AccountInfo accoutInfo =  accountInfoService.validateUser(user);
        Boolean falg=false;
        String code1 =validateCode.createCode(falg,6);
        if(username.contains("@")){
            mailsend.sendMail(code1, username);
            EmailPinCacheUtils.put(username, code1);
        }else{
            cellPhoneMessage.sendPhoneMessage(username, code1); 
            PINCacheUtils.put(username, code1);
        }
        session.setAttribute("vusername", username);
        return "success";
    }
    
    
    @ResponseBody
    @RequestMapping("modifyPassword")
    public Map<String,String> modifyPassword(AccountInfo user,String newPassword,String confirmPassword,String pmodify) throws Exception{
        Map<String,String> result = new HashMap<String,String>();
        if(StringUtils.isBlank(newPassword)){
            result.put("mresult", "200");
            return result;
        }
        if(StringUtils.isBlank(confirmPassword)){
            result.put("mresult", "201");
            return result;
        }
        if(!newPassword.equals(confirmPassword)){
            result.put("mresult", "202");
            return result;
        }
        
        AccountInfo accountInfo= accountInfoService.validateUser(user);
        if(StringUtils.isNotBlank(user.getPassWord())){
            if(!SystemService.validatePassword(user.getPassWord(),accountInfo.getPassWord())){
                result.put("mresult", "204");
                return result;
            }
        }else if(pmodify.equals("true")){
            result.put("mresult", "205");
            return result;
        }
        if(user.getPassWord().equals(newPassword)){
            result.put("mresult", "206");
            return result; 
        }
        accountInfo.setPassWord(systemService.entryptPassword(newPassword));
        accountInfoService.save(accountInfo);
        result.put("mresult", "203");
        return result;
    }
    
    @ResponseBody
    @RequestMapping("resetPassword")
    public Map<String,String> resetPassword(AccountInfo user,String newPassword,String confirmPassword) throws Exception{
        Map<String,String> result = new HashMap<String,String>();
        if(StringUtils.isBlank(newPassword)){
            result.put("mresult", "200");
            return result;
        }
        if(StringUtils.isBlank(confirmPassword)){
            result.put("mresult", "201");
            return result;
        }
        if(!newPassword.equals(confirmPassword)){
            result.put("mresult", "202");
            return result;
        }
        AccountInfo accountInfo= accountInfoService.validateUser(user);
        if(accountInfo!=null){
            accountInfo.setPassWord(systemService.entryptPassword(newPassword));
            accountInfoService.save(accountInfo);
            result.put("mresult", "203");
            return result;
        }
        return result;
    }
    
  /*  @ResponseBody
    @RequestMapping
    public void  validateUsername(String username,RedirectAttributes redirectAttributes){
        if(StringUtils.isBlank(username)){
            addMessage(redirectAttributes, Message.getContent("accountinfo.register.username"));
        }
    }
    
    @ResponseBody
    @RequestMapping
    public void  validate(String username,RedirectAttributes redirectAttributes){
        if(StringUtils.isBlank(username)){
            addMessage(redirectAttributes, Message.getContent("accountinfo.register.username"));
        }
    }*/
    
    @ResponseBody
    @RequestMapping(value="validateUser")
    public Map<String,String> validateUser(AccountInfo user) throws Exception{
        Map<String,String> map = new HashMap<String,String>();
        if(StringUtils.isNotBlank(user.getUsername())){
            if(accountInfoService.validateAccountInfo(user).size()>0){
                map.put("valid", "false");
               return map;//"${message:该用户名已经注册}"; 
            }
        }
        if(StringUtils.isNotBlank(user.getTelNum())){
            
            if(accountInfoService.validateAccountInfo(user).size()>0){
                map.put("valid", "false");
               return map;//"${message:该手机号已经注册}"; 
            }
        }
        if(StringUtils.isNotBlank(user.getEmail())){
            if(accountInfoService.validateAccountInfo(user).size()>0){
                map.put("valid", "false");
               return map;//"${message:该邮箱已经注册}"; 
            }
        }
        if(StringUtils.isNotBlank(user.getWechatNum())){
            if(accountInfoService.validateUser(user)!=null){
               return map;//"${message:该微信号已经注册}"; 
            }
        }
        if(StringUtils.isNotBlank(user.getQqNum())){
            if(accountInfoService.validateUser(user)!=null){
               return map;//"${message:该qq号已经注册}"; 
            }
        }
        map.put("valid", "true");
        return map;
    }
    
    public boolean checkIllegalCharacter(String str){
        String pattern = "[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        return m.matches();
    }
    //新闻正文
    @RequestMapping(value="news_info")
    public String  aa(){
        
        return "modules/cms/news_info";
    }
}